<?php

namespace App\Http\Controllers\API;

use App\Babys;
use Illuminate\Support\Facades\Redis;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BabysController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
        header('Access-Control-Allow-Credentials:false');
        // 验证
        $validator = Validator::make($request->all(), [
            'memid' => 'required',
            'nickname' => 'required',
            'gender' => 'required',
            'birthday' => 'required',
            'logos' => 'required'
        ]);

        if ($validator->fails()) {
            return json_encode(['code' => 1, 'msg' => '请重新输入参数']);
        }
        
        $insertData = [
            "memid" => $request->input("memid"),
            "nickname" => $request->input("nickname"),
            "gender" => $request->input('gender'),
            "logos" => $request->input('img'),
            "birthday" => $request->input("birthday")
        ];
        // 存入数据库
        Babys::create($insertData);
        return json_encode(['code' => 0, 'msg' => '添加成功']);
    }
    /**
     *文件上传
     */
    public function upload(Request $request)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
        header('Access-Control-Allow-Credentials:false');

        $img = '';
        if ($request->file('file')) {
            $ext = $request->file('file')->getClientOriginalExtension();
            $realPath = $request->file('file')->getRealPath();
            $fileName = date('YmdHis') . '.' . $ext;
            move_uploaded_file($realPath,
                "../public/storage/" . $fileName);
            $imgs= asset('storage/'.$fileName);
            return json_encode(['code'=>0,'msg'=>'成功','data'=>$imgs]);
        }else{
            return json_encode(['code'=>1,'msg'=>'无图片','data'=>null]);
        }
    }
}
